
var User = require("./../models/user");
var Q = require('q');

var dbUser = {};
//注册
dbUser.signup = function(option){
	 var deferred = Q.defer();
	 var req = {
	 	code: 1,
		message: '注册成功'
	 }
	 option = option || {};
	 if(!option.name || !option.password){
	 	process.nextTick(function(){
	 		req.code = -3;
	 		req.message = "参数错误";
	 		deferred.reject(req);
	 		global.logger.info("参数错误:",JSON.stringify(option));	
	 	});
	 	return deferred.promise;
	 }
	 
	 
	 User.find({name:option.name},(error,result)=>{
		if(error){
			req.code = -2;
	 		req.message = "数据库操作错误";
	 		deferred.reject(req);
			global.logger.error("数据库操作错误1:",error);	
		}else{
			if (result.length > 0) {
		       req.code = -1;
		 	   req.message = "用户名重复";
		 	   deferred.reject(req);
			   global.logger.info("用户名重复:",result);	
	      	} else {
		        user = new User(option)
		        user.save( (err, user) => {
		          if (err) {
		            req.code = -2;
			 		req.message = "数据库操作错误";
			 		deferred.reject(req);
					global.logger.error("数据库操作错误2:",err);	
		          }
		          deferred.resolve(req);
		        })
	      	}			
		}
	});
	
	return deferred.promise;
}

//登录
dbUser.signin = function(option){
	 var deferred = Q.defer();
	 var req = {
	 	code: 1,
		message: '登录成功',
		data:{}
	 }
	 option = option || {};
	 if(!option.name || !option.password){
	 	process.nextTick(function(){
	 		req.code = -3;
	 		req.message = "参数错误";
	 		deferred.reject(req);
	 		global.logger.info("参数错误:",JSON.stringify(option));	
	 	});
	 	return deferred.promise;
	 }
	 
	 
	 User.findOne({name:option.name},(error,result)=>{
		if(error){
			req.code = -2;
	 		req.message = "数据库操作错误";
	 		deferred.reject(req);
			global.logger.error("数据库操作错误1:",error);	
		}else{	
			
			if (!result) {
		       req.code = -4;
		 	   req.message = "用户不存在";
		 	   deferred.reject(req);
			   global.logger.info("用户不存在:",result,option.name);	
	      	} else {
		        if (!!option.password) {
			          result.comparePassword(option.password, (err, isMatch) => {
			            if (err) {
			                req.code = -2;
					 		req.message = "数据库操作错误";
					 		deferred.reject(req);
							global.logger.error("数据库操作错误2:",err);
			            }
			            if (isMatch) {
			              result["password"] = null;
			              delete result["password"];
			              req.data = result;
			              deferred.resolve(req);
			              global.logger.info('success');
			            } else {
			            	req.code = -5;
			            	req.message = "密码错误";
			             	deferred.reject(req);
			              global.logger.info('password is not meached');
			            }
			          })
		        } else {
		        	req.code = -5;
			        req.message = "登录失败";
		          	deferred.reject(req);
		        }
		      }
	      	}			
	});
	
	return deferred.promise;
}


module.exports = dbUser;
